import { StatusCodes } from 'http-status-codes';

export const ErrorCodes = {
  // Authentication Errors (400-499)
  INVALID_CREDENTIALS: {
    code: StatusCodes.UNAUTHORIZED,
    message: 'Invalid email or password',
  },
  TOKEN_EXPIRED: {
    code: StatusCodes.UNAUTHORIZED,
    message: 'Token has expired',
  },
  INVALID_TOKEN: {
    code: StatusCodes.UNAUTHORIZED,
    message: 'Invalid token',
  },
  NO_TOKEN: {
    code: StatusCodes.UNAUTHORIZED,
    message: 'No token provided',
  },
  UNAUTHORIZED: {
    code: StatusCodes.UNAUTHORIZED,
    message: 'Unauthorized access',
  },
  FORBIDDEN: {
    code: StatusCodes.FORBIDDEN,
    message: 'Access forbidden',
  },
  ACCOUNT_DISABLED: {
    code: StatusCodes.FORBIDDEN,
    message: 'Account has been disabled',
  },

  // Resource Errors (400-499)
  NOT_FOUND: {
    code: StatusCodes.NOT_FOUND,
    message: 'Resource not found',
  },
  ALREADY_EXISTS: {
    code: StatusCodes.CONFLICT,
    message: 'Resource already exists',
  },
  INVALID_REQUEST: {
    code: StatusCodes.BAD_REQUEST,
    message: 'Invalid request parameters',
  },
  VALIDATION_ERROR: {
    code: StatusCodes.BAD_REQUEST,
    message: 'Validation failed',
  },

  // Server Errors (500-599)
  INTERNAL_SERVER_ERROR: {
    code: StatusCodes.INTERNAL_SERVER_ERROR,
    message: 'Internal server error',
  },
  DATABASE_ERROR: {
    code: StatusCodes.INTERNAL_SERVER_ERROR,
    message: 'Database operation failed',
  },
  SERVICE_UNAVAILABLE: {
    code: StatusCodes.SERVICE_UNAVAILABLE,
    message: 'Service temporarily unavailable',
  },

  // Business Logic Errors (1000+)
  INSUFFICIENT_PERMISSIONS: {
    code: 1001,
    message: 'Insufficient permissions to perform this action',
  },
  RATE_LIMIT_EXCEEDED: {
    code: 1002,
    message: 'Rate limit exceeded',
  },
  INVALID_OPERATION: {
    code: 1003,
    message: 'Invalid operation',
  },
  DATA_INTEGRITY_ERROR: {
    code: 1004,
    message: 'Data integrity violation',
  },
} as const;

export type ErrorCode = keyof typeof ErrorCodes;

export interface ErrorResponse {
  code: number;
  message: string;
  details?: any;
  stack?: string;
}

export const createErrorResponse = (
  error: ErrorCode | string,
  details?: any,
  stack?: string
): ErrorResponse => {
  if (typeof error === 'string' && error in ErrorCodes) {
    const errorCode = error as ErrorCode;
    return {
      code: ErrorCodes[errorCode].code,
      message: ErrorCodes[errorCode].message,
      ...(details && { details }),
      ...(stack && process.env.NODE_ENV !== 'production' && { stack }),
    };
  }

  return {
    code: StatusCodes.INTERNAL_SERVER_ERROR,
    message: typeof error === 'string' ? error : 'Internal server error',
    ...(details && { details }),
    ...(stack && process.env.NODE_ENV !== 'production' && { stack }),
  };
};
